<?php
class threadModel extends RelationModel
{
    
    //自动完成
    protected $_auto = array(
        array('addTime', 'time', 1, 'function'),
        array('userId', 'getAdminId', 1, 'function'),
    );
   
    
    protected $_link = array(
        'user' => array(
            'mapping_type' => BELONGS_TO,
            'class_name' => 'admin',
            'foreign_key' => 'userId',
            'mapping_fields'=>'realName,userName',
        )
    );
	

	/**
	 * 获得指定帖子的回复内容
	 */
	public function getThreadReplies($threadId){
		$list = array();
		$replies = D('ThreadReplies')->alias('r')->field('r.*, u.realName')
				->join(C('DB_PREFIX')."admin AS u ON u.id = r.userId")
				->where("r.threadId={$threadId} AND r.status=1")->order('addTime DESC')->select();
	
		foreach ($replies as $row){
			$temp = array();
			
			$temp['realName']	= $row['realName'];
			$temp['comment']	= $row['content'];
			$temp['addTime']	= date('Y-m-d H:i:s', $row['addTime']);
			$temp['icon']		= D('admin')->getIcon($row['userId']); 
			$attachment			= $this->getAttachment($row['attachment']);
			if($attachment){
				foreach($attachment as $a){
					foreach ($a as $b){
						$temp['attachment'][] = $b;
					}
				}
			}else{
				$temp['attachment'] = NULL;
			}
			$list[] = $temp;
		}
		return $list;
	}
	
	/**
	 * 处理附件信息
	 */
	public function getAttachment($attachment){
		$data = array();
		if($attachment){
			$attachment = unserialize($attachment);
			foreach($attachment as $key=>$val){
				foreach($val as $row){
					$data[$key][] = __ROOT__.C('pin_attach_path').$row;
				}
			}
		}
		return $data;
	}
    
    /**
     * 插入后，也要在post表增加一条记录
     */ 
    protected function _after_insert($data,$option){
        if($data['id']){
            $newData['threadId'] = $data['id'];
            $newData['title']    = $data['title'];            
            $newData['addTime']  = time();
            $newData['userId']   = $data['userId'];
            $newData['content']  = $data['content'];
            $newData['attachment']= $data['attachment'];
            $newData['floor']    = '1';
            M('thread_replies')->add($newData);
        }
    }
    
    /**
     * 插入后，也要在post表增加一条记录
     */     
    protected function _after_update($data,$option){
        if($data['id']){
            $info = $this->where(array('id'=>$data['id']))->find();
            if($info){
                $newData['threadId'] = $info['id'];
                $newData['userId'] = $info['userId'];
                $newData['title'] = $info['title'];            
                $newData['addTime'] = time();
                $newData['content'] = $info['content'];
                $newData['attachment']= $info['attachment'];
                M('thread_replies')->where(array('floor'=>1,'threadId'=>$data['id']))->limit(1)->save($newData);
            }
        }        
    }
    
    

    
    
}